package Thread;
class  MyBlockQueue{
    Object locker = new Object();
    //数组
    private  String[] arr =null;
    //队首
    private int front;
    //队尾
    private  int rear;
    public  int size = 0;
    public  MyBlockQueue(int capacity){
        arr = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (locker){

            while (size>=arr.length){
                //队列满了，需要阻塞
                locker.wait();
            }
            arr[rear] =  elem;
            rear++;
            if (rear>=arr.length){
                rear=0;
            }
            size++;
            locker.notify();
        }

    }
    public String take() throws InterruptedException {
        synchronized (locker){
            while (size ==0){
                //队列为空，需要阻塞
                locker.wait();
            }
            String ret = arr[front];
            front++;
            if (front >=arr.length){
                front =0;
            }
            size--;
            locker.notify();
            return ret;
        }
    }
}
public class Demo29 {
    public static void main(String[] args) {
        MyBlockQueue queue = new MyBlockQueue(1000);
        Thread producer  = new Thread(()->{
            int n=0;
            while(true){
                n++;
                try {
                    queue.put(n+"");
                    System.out.println("生产者元素："+n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread consumer = new Thread(()->{
            while (true){
                String n =null;
                try {
                    n = queue.take();
                    System.out.println("消费者元素："+n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        producer.start();
        consumer.start();
    }
}
